<template>
  <canvas canvas-id="uChart" class="chart-container"></canvas>
</template>

<script setup>
import uCharts from '@qiun/ucharts'
import { onMounted, ref, watch } from 'vue'
import { jsonString, string } from '../uni_modules/uview-plus/libs/function/test'

const props=defineProps({
  options: {
    type: Object,
    required: true,
    default: () => ({}) // 默认值防止 undefined
  }
})

const chartInstance = ref(null)

onMounted(() => {
  if (!props.options) {
    console.error('options is not provided!')
    return
  }
  
  const context = uni.createCanvasContext('uChart')
  chartInstance.value = new uCharts({
    canvasId: 'uChart',
    type: props.options.type || 'line', // 默认图表类型
    context,
    width: uni.getSystemInfoSync().windowWidth - 40, // 减去左右 padding
    height: 200,
    series: props.options.series,
    categories: props.options.categories,
    ...props.options
  })
})

// 监听 options 的变化，动态更新图表
watch(() => props.options, (newOptions) => {
  if (chartInstance.value && newOptions) {
    chartInstance.value.updateData({
      series: newOptions.series,
      categories: newOptions.categories
    })
  }
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 200rpx;
}
</style>